using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;

namespace vCrossPost.PingFM
{
    public class WebClientEx : WebClient
    {
        public T ExecuteMethod<T>(string methodName, NameValueCollection data)
        {
            using (var buffer = new MemoryStream(UploadValues("http://api.ping.fm/v1/" + methodName, "POST", data)))
                return Serialization.Deserialize<T>(buffer);
        }

        public T UploadValues<T>(string address, NameValueCollection data)
        {
            using (var buffer = new MemoryStream(UploadValues(address, data)))
                return Serialization.Deserialize<T>(buffer);
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);

            var httpRequest = request as HttpWebRequest;
            if (httpRequest != null)
            {
                // Headers stolen from Ping.fm API in C# library - Adam Duffy.
                httpRequest.Headers.Add("Accept-Language", "en-us");
                httpRequest.Accept =
                    "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                httpRequest.UserAgent = "vCrossPost";
            }

            return request;
        }
    }
}